// app/page/EmployeePerformanceScreen.tsx
import { Ionicons } from "@expo/vector-icons";
import { Stack } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    ActivityIndicator,
    Dimensions,
    FlatList,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import DateTimePickerModal from "react-native-modal-datetime-picker";
import StoreModal from "../components/storeModal";

const screenWidth = Dimensions.get("window").width;

type Employee = {
    id: string;
    name: string;
    serviceCount: number;
    rechargeCount: number;
};

type StoreEntry = { GUID: string; Name: string };

const mockStores: StoreEntry[] = [
    { GUID: "1", Name: "天河店" },
    { GUID: "2", Name: "白云店" },
    { GUID: "3", Name: "海珠店" },
];

const mockEmployees: Record<string, Employee[]> = {
    "1": [
        { id: "e1", name: "小张", serviceCount: 8, rechargeCount: 3 },
        { id: "e2", name: "小李", serviceCount: 5, rechargeCount: 1 },
    ],
    "2": [
        { id: "e3", name: "小王", serviceCount: 10, rechargeCount: 4 },
        { id: "e4", name: "小陈", serviceCount: 7, rechargeCount: 2 },
    ],
    "3": [{ id: "e5", name: "小刘", serviceCount: 4, rechargeCount: 1 }],
};

export default function EmployeePerformanceScreen() {
    const [visible, setVisible] = useState(false);
    const [currentStore, setCurrentStore] = useState<StoreEntry>({ GUID: "1", Name: "天河店" });

    const [dateRange, setDateRange] = useState<"day" | "month" | "year">("day");
    const [employees, setEmployees] = useState<Employee[]>([]);
    const [loading, setLoading] = useState(false);

    const [selectedDate, setSelectedDate] = useState(new Date());
    const [showDatePicker, setShowDatePicker] = useState(false);

    const [summary, setSummary] = useState({ totalService: 0, totalRecharge: 0 });

    useEffect(() => {
        loadPerformanceData();
    }, [currentStore, selectedDate]);

    const loadPerformanceData = () => {
        setLoading(true);
        setTimeout(() => {
            const data = mockEmployees[currentStore.GUID] || [];
            setEmployees(data);
            setSummary({
                totalService: data.reduce((sum, e) => sum + e.serviceCount, 0),
                totalRecharge: data.reduce((sum, e) => sum + e.rechargeCount, 0),
            });
            setLoading(false);
        }, 400);
    };

    const renderItem = ({ item }: { item: Employee }) => (
        <View style={styles.card}>
            <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
                <Text style={styles.name}>{item.name}</Text>
                <Ionicons name="person-circle-outline" size={28} color="#4e8ef7" />
            </View>
            <View style={styles.divider} />
            <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                <Text style={styles.data}>💇‍♀️ 服务次数：{item.serviceCount}</Text>
                <Text style={styles.data}>💳 充卡次数：{item.rechargeCount}</Text>
            </View>
        </View>
    );

    return (
        <>
            <Stack.Screen
                options={{
                    headerTitle: () => (
                        <TouchableOpacity onPress={() => setVisible(true)}>
                            <Text style={styles.headerStoreText}>{currentStore.Name} ▼</Text>
                        </TouchableOpacity>
                    ),
                }}
            />

            <View style={styles.container}>
                {/* 汇总 */}
                <View style={styles.summaryCard}>
                    <View style={styles.summaryItem}>
                        <Text style={styles.summaryNumber}>{summary.totalService}</Text>
                        <Text style={styles.summaryLabel}>总服务次数</Text>
                    </View>
                    <View style={styles.summaryItem}>
                        <Text style={styles.summaryNumber}>{summary.totalRecharge}</Text>
                        <Text style={styles.summaryLabel}>总充卡次数</Text>
                    </View>
                </View>
                {/* 时间筛选 */}
                <View style={styles.filterRow}>
                    <TouchableOpacity
                        onPress={() => {
                            setDateRange("day");
                        }}
                        style={[styles.filterButton, dateRange === "day" && styles.active]}
                    >
                        <Text style={styles.filterText}>今日</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={() => {
                            setDateRange("month");
                        }}
                        style={[styles.filterButton, dateRange === "month" && styles.active]}
                    >
                        <Text style={styles.filterText}>本月</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={() => {
                            setDateRange("year");
                        }}
                        style={[styles.filterButton, dateRange === "year" && styles.active]}
                    >
                        <Text style={styles.filterText}>今年</Text>
                    </TouchableOpacity>
                </View>

                {/* 日期选择按钮 */}
                <TouchableOpacity
                    onPress={() => {
                        setShowDatePicker(true);
                    }}
                    style={[styles.filterButton, { alignSelf: "center", marginBottom: 14 }]}
                >
                    <Text style={styles.filterText}>{selectedDate.toLocaleDateString()}</Text>
                    <Ionicons name="calendar-outline" size={16} style={{ marginLeft: 4 }} />
                </TouchableOpacity>

                {loading ? (
                    <ActivityIndicator size="large" color="#007aff" style={{ marginTop: 40 }} />
                ) : (
                    <FlatList data={employees} renderItem={renderItem} keyExtractor={(item) => item.id} style={{ marginTop: 10 }} />
                )}
            </View>

            <StoreModal visible={visible}
                GUID="1"
                onCancle={() => { setVisible(false) }}
                onConfirm={(item) => {
                    setVisible(false);
                    setCurrentStore(item);
                }} />
            {/* 日期选择弹框 */}
            <DateTimePickerModal
                isVisible={showDatePicker}
                mode="date"
                date={selectedDate}
                onConfirm={(date) => {
                    setSelectedDate(date);
                    setShowDatePicker(false);
                }}
                onCancel={() => setShowDatePicker(false)}
            />
        </>
    );
}

const styles = StyleSheet.create({
    container: { flex: 1, backgroundColor: "#f7f9fb", padding: 16 },
    headerStoreText: { fontSize: 18, fontWeight: "600", color: "#007aff" },

    summaryCard: {
        flexDirection: "row",
        justifyContent: "space-around",
        backgroundColor: "#fff",
        borderRadius: 12,
        padding: 16,
        marginBottom: 14,
        shadowColor: "#000",
        shadowOpacity: 0.05,
        shadowOffset: { width: 0, height: 1 },
        shadowRadius: 4,
        elevation: 2,
    },
    summaryItem: { alignItems: "center" },
    summaryNumber: { fontSize: 18, fontWeight: "bold", color: "#4e8ef7" },
    summaryLabel: { fontSize: 12, color: "#555", marginTop: 4 },

    filterRow: { flexDirection: "row", justifyContent: "space-around", marginBottom: 14 },
    active: { backgroundColor: "#007aff22" },
    filterButton: {
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: 6,
        paddingHorizontal: 14,
        borderRadius: 20,
        backgroundColor: "#eee",
    },
    filterText: { fontSize: 14, color: "#333" },

    card: {
        backgroundColor: "#fff",
        borderRadius: 12,
        padding: 14,
        marginVertical: 6,
        shadowColor: "#000",
        shadowOpacity: 0.05,
        shadowOffset: { width: 0, height: 1 },
        shadowRadius: 4,
        elevation: 2,
    },
    name: { fontSize: 16, fontWeight: "bold", color: "#222" },
    divider: { height: 1, backgroundColor: "#eee", marginVertical: 8 },
    data: { fontSize: 14, color: "#555", marginTop: 2 },

    modalOverlay: { flex: 1, backgroundColor: "rgba(0,0,0,0.3)", justifyContent: "center", alignItems: "center", paddingHorizontal: 16 },
    modalContent: {
        width: Math.min(screenWidth * 0.9, 400),
        maxHeight: "80%",
        backgroundColor: "#fff",
        borderRadius: 12,
        padding: 20,
    },
    modalTitle: { fontSize: 16, fontWeight: "600", marginBottom: 10, textAlign: "center" },
    storeItem: { paddingVertical: 10, alignItems: "center" },
    storeText: { fontSize: 15, color: "#333" },
    activeStoreText: { color: "#4e8ef7", fontWeight: "bold" },
    cancelButton: { marginTop: 10, alignItems: "center" },
});